import { Query } from '../../utils/Query'

var R_source
var R_layer
var shape
// 显示路况
const ShowRoad = (map) => {
  // 查询地图服务的线要素
  var service = { name: 'guanggu', layerId: 1 }
  var where = '车流量' > 0
  Query.queryByAttr({ where, service, callback: querySuccess })
  // 矢量化矢量图层layer用于高亮显示结果
  R_source = new ol.source.Vector({ wrapX: false })
  R_layer = new ol.layer.Vector({
    source: R_source
  })

  function querySuccess(e) {
    var feature = e.SFEleArray //获取到道路数组
    //初始化Zondy.Format.PolygonJSON类
    var format = new Zondy.Format.PolygonJSON()
    //将MapGIS要素JSON反序列为ol.Feature类型数组
    var features = format.read(e)
    //获取每个道路的坐标
    for (var i = 0; i < feature.length; i++) {
      var flow = Number(feature[i].AttValue[4]) //获取车流量
      var colorIndex = Math.floor(flow / 400 - 1)
      //根据车流量赋予线不同的颜色
      var color = new Array(
        '#2d9400',
        '#87be00',
        '#fff000',
        '#ff8400',
        '#ff1900'
      )
      //设置线的style样式
      var style = new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: color[colorIndex],
          width: 6
        })
      })
      //给每个线要素设置颜色
      features[i].setStyle(style)
    }
    R_source.addFeatures(features) //添加到数据源里
    map.addLayer(R_layer)
  }

  // 图例数组
  var dataObj = [
    {
      tname: '非常拥堵',
      color: '#ff1900'
    },
    {
      tname: '拥堵',
      color: '#ff8400'
    },
    {
      tname: '行驶缓慢',
      color: '#fff000'
    },
    {
      tname: '基本畅通',
      color: '#87be00'
    },
    {
      tname: '畅通',
      color: '#2d9400'
    }
  ]

  // 根据图例经纬度坐标绘制canvas
  var removeData = {
    JD: 114.4209,
    WD: 30.4616
  }
  var canvas = document.createElement('canvas')
  shape = new ol.Feature({
    geometry: new ol.geom.Point([removeData.JD, removeData.WD])
  })
  // 绘制图例函数
  function drawMapTuliMethod() {
    var ctx = canvas.getContext('2d')
    var yheight = 50
    yheight += dataObj.length * 27 //计算canvas高度
    canvas.width = 140
    canvas.height = yheight

    /*设置图例样式*/
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, 200, yheight) //绘制底图
    ctx.font = '20px Arial'
    ctx.fillStyle = '#000'
    ctx.fillText('图例', canvas.width / 5, 25)
    for (var i = 0; i < dataObj.length; i++) {
      //实现文字前面带色块
      ctx.fillStyle = dataObj[i].color //块颜色
      ctx.fillRect(10, 70 + (i - 1) * 25, 15, 15) //颜色块：x,y,w,h

      ctx.font = '18px Arial'
      ctx.fillStyle = '#555'
      ctx.fillText(dataObj[i].tname, 45, 84 + (i - 1) * 25) //文字
    }
    //将canvas添加到样式中
    var style = new ol.style.Style({
      image: new ol.style.Icon({
        img: canvas,
        imgSize: [canvas.width, canvas.height]
      })
    })
    shape.setStyle(style)
    R_layer.getSource().addFeature(shape)
  }

  drawMapTuliMethod()
}
// 隐藏路况
const hideRoad = (R_source, R_layer, shape) => {
  // 清空图层
  R_source.clear()
  // 清除图例
  R_layer.getSource().removeFeature(shape)
}

export { ShowRoad, hideRoad, R_source, R_layer, shape }